package com.tcoiss.datafactory.util;

import com.alibaba.fastjson.JSON;
import com.tcoiss.common.core.constant.Constants;
import com.tcoiss.common.core.utils.SpringUtils;
import com.tcoiss.common.core.utils.StringUtils;
import com.tcoiss.common.redis.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class ThreadUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{

    private static final Logger LOGGER = LoggerFactory.getLogger(ThreadUncaughtExceptionHandler.class);

    private final static long EXPIRE_TIME = Constants.KD_TOKEN_EXPIRE * 10;
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        LOGGER.error("捕获到线程发生的异常，线程信息:[{}]", JSON.toJSONString(t), e);
        //将异常写入方案日志中
        RedisService redisService = SpringUtils.getBean(RedisService.class);
        LOGGER.info(redisService.toString());
        String ex = redisService.getCacheObject("ThreadException");
        if(StringUtils.isNotEmpty(ex)){
            redisService.setCacheObject("ThreadException",ex+",线程【"+t.getName()+"】执行异常："+e.getMessage(),EXPIRE_TIME, TimeUnit.SECONDS);
        }else{
            redisService.setCacheObject("ThreadException","线程【"+t.getName()+"】执行异常："+e.getMessage(),EXPIRE_TIME, TimeUnit.SECONDS);
        }
    }
}
